import json
import logging
import os
import shutil
from datetime import datetime, timedelta
import allure
import paramiko

from config.config import ppa_prefix_to_api


def read_json_file(file_path):
    with open(file_path, 'r') as f:
        json_data = json.load(f)
        data_list = []
        for case_data in json_data:
            data = tuple(case_data.values())
            data_list.append(data)
        return data_list


@allure.step("Update sys_biz_date: {date}")
def update_sys_biz_date(date):
    """
    通过SSH连接更新远程Linux服务器上的 sys_biz_date
    
    Args:
        date: 日期字符串，格式为 YYYY-MM-DD
    """
    from config.config import remote_server, remote_port, remote_username, remote_password, ppa_agent_folder_path

    properties_file_path = f"{ppa_agent_folder_path}/program/config/qa_linux/application.properties"

    try:
        # 创建SSH连接
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        password_str = str(remote_password)
        port_int = int(remote_port)
        ssh.connect(remote_server, port=port_int, username=remote_username, password=password_str)

        # 读取远程文件
        stdin, stdout, stderr = ssh.exec_command(f"cat {properties_file_path}")
        content = stdout.read().decode('utf-8')

        # 替换 sys_biz_date
        lines = content.split('\n')
        replaced = False
        new_lines = []

        for line in lines:
            if line.startswith("sys_biz_date="):
                new_lines.append(f"sys_biz_date={date}")
                replaced = True
            else:
                new_lines.append(line)

        if not replaced:
            new_lines.append(f"sys_biz_date={date}")

        new_content = '\n'.join(new_lines)

        # 写回远程文件
        sftp = ssh.open_sftp()
        with sftp.file(properties_file_path, 'w') as f:
            f.write(new_content)

        sftp.close()
        ssh.close()

        logging.info(f"[INFO] Updated sys_biz_date to {date} in remote file {properties_file_path}")

    except Exception as e:
        logging.error(f"[ERROR] Failed to update sys_biz_date: {e}")


def copy_files_by_prefix_to_specific_folders(source_directory, prefix_to_target_folder_map=ppa_prefix_to_api):
    """
    根据文件名前缀将文件复制到指定文件夹
    
    Args:
        source_directory: 源目录
        prefix_to_target_folder_map: 前缀到目标文件夹的映射字典
    """
    if not os.path.exists(source_directory):
        logging.warning(f"[WARN] Source directory does not exist: {source_directory}")
        return

    for filename in os.listdir(source_directory):
        source_file_path = os.path.join(source_directory, filename)
        if os.path.isfile(source_file_path):
            matched = False
            for prefix, target_dir in prefix_to_target_folder_map.items():
                if filename.startswith(prefix):
                    os.makedirs(target_dir, exist_ok=True)
                    target_file_path = os.path.join(target_dir, filename)
                    try:
                        shutil.copy2(source_file_path, target_file_path)
                        logging.info(f"[INFO] Copied '{filename}' to '{target_dir}'")
                        matched = True
                        break
                    except Exception as ex:
                        logging.error(f"[ERROR] Copy '{filename}' to '{target_dir}' failed: {ex}")
            if not matched:
                logging.info(f"[INFO] File '{filename}' does not match any prefix, skipped copy.")

